package com.langsin.my0628;

import com.langsin.bean.User;
import com.langsin.sunzhaofa.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class SunZhaoFaTest {
    SqlSession sqlSession=null;
    //之前加载
    @Before
    public void testBefore() throws IOException {
        //mybatis 一级缓存 存在sqlSession的 内存 map中
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory =builder.build(stream);
        sqlSession = sessionFactory.openSession();
    }


    //对象 必须实现序列化
    //必须配置文件<setting name="cacheEnabled" value="true"/>
    // 必须在map中开启<cache/>
    @Test
    public void testCache2() throws IOException {

        //mybatis 一级缓存 存在sqlSession的 内存 map中
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);

        // 第一个会话
        SqlSession sqlSession1 = sessionFactory.openSession();
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = mapper1.queryById(702);
        System.out.println(user1);
        sqlSession1.close();

        //休息2秒
        try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}
        System.out.println("休眠2秒！");


        // 第二个会话
        SqlSession sqlSession2 = sessionFactory.openSession();
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = mapper2.queryById(702);
        System.out.println(user2);
        sqlSession2.close();
    }
    @Test
    public void testCache1() throws IOException {
        //第一次查询
        UserMapper userMapper =sqlSession.getMapper(UserMapper.class);
        User user=userMapper.queryById(702);
        System.out.println(user.toString());

        //休息2秒
        try {Thread.sleep(2000);}catch (Exception e){e.printStackTrace();}

        //第二次查询
        User user1=userMapper.queryById(702);
        System.out.println(user1.toString());
        //如果进行操作，则缓存会失效


    }




}
